﻿// 4. Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using the method 
// Array.BinSearch() finds the largest number in the array which is ≤ K. 

using System;

class BinarySearchForKElement
{
    static void Main()
    {
        // get the array's dimension
        Console.Write("Enter the dimension of the array : ");
        string sizeStr = Console.ReadLine();
        int size;
        while (!int.TryParse(sizeStr, out size))
        {
            Console.Write("Invalid input. Enter again the array's dimension : ");
            sizeStr = Console.ReadLine();
        }

        // get number K
        Console.Write("Enter number K : ");
        string kStr = Console.ReadLine();
        int numberK;
        while (!int.TryParse(kStr, out numberK))
        {
            Console.Write("Invalid input. Enter again the number of columns of the matrix : ");
            kStr = Console.ReadLine();
        }

        // define the array
        int[] array = new int[size];
        // enter values for the cells
        Console.WriteLine("Enter the cells of the array:");
        for (int num = 0; num < size; num++)
        {
                Console.Write("array[{0}] = ", num);
                array[num] = int.Parse(Console.ReadLine());
        }

        // sort the array
        Array.Sort(array);

        // find the index of number K
        int index = Array.BinarySearch(array, numberK);

        // check the value and display the result
        if (array[0] > numberK)
        {
            Console.WriteLine("All numbers in the array are larger than K.");
        }
        else if (index >= 0)
        {
            Console.WriteLine("The largest number in the array which is <= K is {0}.", array[index]);
        }
        else
        {
            Console.WriteLine("The largest number in the array which is <= K is {0}.", array[~index - 1]);
        }
    }
}
